//
//  EntityUtil.m
//  LOU
//
//  Created by iMacOne on 15/11/11.
//  Copyright © 2015年 UNOHACHA. All rights reserved.
//

#import "EntityUtil.h"
#import <objc/runtime.h>
#import "ToolUtil.h"
@implementation EntityUtil
// utf8编码过的json字符串转map, 可用在和网页交互
+ (NSDictionary*)utf8Map:(NSString*)str
{
    NSString * json = [NSString stringWithString:[str stringByRemovingPercentEncoding]];
    return [EntityUtil jsonToMapArray:json];
}
#pragma mark 对象转map
+ (NSMutableDictionary*)objToMap:(id)obj
{
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    unsigned int propsCount;
    objc_property_t * props = class_copyPropertyList([obj class], &propsCount);
    for (int i = 0; i < propsCount; i++) {
        objc_property_t prop = props[i];
        NSString * propName = [NSString stringWithUTF8String:property_getName(prop)];
        id value = [obj valueForKey:propName];
        [dic setObject:(value == nil ? @"":value) forKey:propName];
    }
    return dic;
}
#pragma mark map转对象
+ (id)mapToObj:(NSMutableDictionary*)map {
    return nil;
}
// 对象转json
+ (NSString*)toJson:(id)obj {
    if (nil == obj) {
        return @"{}";
    }
    if ([obj isKindOfClass:[NSString class]]) {
        return obj;
    }
    if ([obj isKindOfClass:[NSDictionary class]] || [obj isKindOfClass:[NSMutableDictionary class]] || [obj isKindOfClass:[NSArray class]] || [obj isKindOfClass:[NSMutableArray class]] ) {
        return [EntityUtil mapArrayToJson:obj];
    }
    return [EntityUtil mapArrayToJson:[EntityUtil objToMap:obj]];
}

// 拼接获得上传的参数
+ (NSString*)getUploadParam:(int)cut isUpload:(BOOL)isUpload
{
    NSArray * values = @[[NSNumber numberWithInt:cut],[NSNumber numberWithBool:isUpload]];
    NSMutableDictionary * dic = [EntityUtil createMap:@[@"cut",@"upload"] values:values];
    return [EntityUtil encodeURL:[EntityUtil mapArrayToJson:dic]];
}
#pragma mark url编码
+ (NSString*)encodeURL:(NSString *)string
{
    if ([ToolUtil isBlank:string]) {
        return @"";
    }
    return [string stringByRemovingPercentEncoding];
}
// json转字典或数组
+ (id)jsonToMapArray:(NSString*)json
{
    NSData * data = [json dataUsingEncoding:NSUTF8StringEncoding];
    return [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
}
// 对象转json
+ (NSString*)mapArrayToJson:(id)obj {
    if (nil == obj) {
        return @"{}";
    }
    NSData *data = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:nil];
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

#pragma mark 根据key和value创建dic
+ (NSMutableDictionary*)createMap:(NSArray*)keys values:(NSArray*)values {
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    if (nil != keys && nil != values && keys.count == values.count) {
        for (int i = 0; i < keys.count; i++) {
            [dic setValue:values[i] forKey:keys[i]];
        }
    }
    return dic;
}
@end
